<template>
	<!--
	 本页面模板教程：https://ext.dcloud.net.cn/plugin?id=2717
	 uni-list 文档：https://ext.dcloud.net.cn/plugin?id=24
	 uniCloud 文档：https://uniapp.dcloud.io/uniCloud/README
	 unicloud-db 组件文档：https://uniapp.dcloud.net.cn/uniCloud/unicloud-db-component
	 DB Schema 规范：https://uniapp.dcloud.net.cn/uniCloud/schema
	 -->
	<view class="article">
		<!-- #ifdef APP-PLUS -->
		<uni-nav-bar :statusBar="true" :border="false"></uni-nav-bar>
		<!-- #endif -->
		<unicloud-db v-slot:default="{data, loading, error, options}" collection="t_shop_goods" :where="goodWhere">
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<view  v-for="(item,index) in data" :key="index">
					<u-swiper :list="thumb" indicator indicatorMode="dot" circular height="950rpx"></u-swiper>
					<view class="content">
						<view class="title" style="font-size: 32rpx;">{{ item.name }}</view>
						<view class="desc" style="font-size: 12px;color: #999999;letter-spacing: 0;line-height: 18px;margin: 6px 0;">
						{{ item.descript }}</view>
						<view class="price" style="color: red;font-size: 24rpx;">{{ formatPrice(item.price) }}</view>
						<u-row gutter="16" class="express">
							<u-col :span="6" style="color: #999;font-size: 24rpx;padding: 10rpx 17rpx;">运费：免运费</u-col>
							<u-col :span="6" style="color: #999;font-size: 24rpx;padding: 10rpx 0rpx;">剩余：{{item.stock}}</u-col>
						</u-row>
					</view>
				</view>
			</view>
		</unicloud-db>    
		<view class="goods-carts">
			<uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick" @buttonClick="buttonClick" />
		</view>
		<uni-popup v-if="goods != null" ref="popup" type="bottom" background-color="#fff">
			<view class="sku">
				<view class="goods">
					<u-row>
						<u-col :span="4" class="left">
							<u-image width="170rpx" height="170rpx" :src="'https://zhy-demo.oss-cn-hangzhou.aliyuncs.com/upload/' + goods.pic"></u-image>
						</u-col>
						<u-col :span="8" class="right">
							<view class="price">{{formatPrice(goods.price)}}</view>
							<view class="stock">剩余<text class="stock_num">{{goods.stock}}</text>件</view>
							<!-- <template v-if="!sku.none_sku">
								<view class="tips">{{hasSel?'已选择':'请选择'}}
									<text v-for="(item,index) in sku.tree" :key="index" style="padding-left:10rpx;">
						
										{{item.sel?item.v[parseInt(item.sel)].name:item.k}}
									</text>
								</view>
							</template> -->
						</u-col>
					</u-row>
				</view>
				<view class="count u-flex u-row-between">
					<view>购买数量</view>
					<view>
						<u-number-box v-model="count" :max="goods.stock"></u-number-box>
					</view>
				</view>
				<view class="action">
					<u-button type="error" shape="circle" @click="action">确定</u-button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	// #ifdef APP
	import UniShare from '@/uni_modules/uni-share/js_sdk/uni-share.js';
	const uniShare = new UniShare()
	// #endif
	const db = uniCloud.database();
	const dbCmd = db.command
	const dbGoods = db.collection("t_shop_goods")
	const dbCart = db.collection("t_shop_cart")
	const readNewsLog = db.collection('read-news-log')
	const favoriteDB = db.collection("t_shop_favorite")
	export default {
		// #ifdef APP
		onBackPress({from}) {
			if(from == 'backbutton'){
				if(uniShare.isShow){
					this.$nextTick(function(){
						console.log(uniShare);
						uniShare.hide()
					})
				}
				return uniShare.isShow;
			}
		},
		// #endif
		data() {
			return {
				// 当前显示 _id
				id: "",
				title: 'title',
				goodWhere:"",
				count: 1,
				actionType: "buy",
				thumb: [],
				// 数据表名
				// 查询字段，多个字段用 , 分割
				field: 'user_id.username,user_id._id,avatar,excerpt,last_modify_date,comment_count,like_count,title,content',
				formData: {
					noData: '<p style="text-align:center;color:#666">详情加载中...</p>'
				},
				goods: null,
				optionsKey: true,
				options: [{
						icon: 'shop',
						text: '店铺'
					}, {
						icon: 'heart',
						text: '收藏',
						info: 2,
						// infoBackgroundColor: '#007aff',
						// infoColor: "#f5f5f5"
					}, {
						icon: 'cart',
						text: '购物车',
						// info: 2
					}],
					buttonGroup: [{
							text: '加入购物车',
							backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
							color: '#fff'
						},
						{
							text: '立即购买',
							backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
							color: '#fff'
						}
					],
			}
		},
		computed: {
			uniStarterConfig() {
				return getApp().globalData.config
			},
			where(){
				//拼接where条件 查询条件 ,更多详见 ：https://uniapp.dcloud.net.cn/uniCloud/unicloud-db?id=jsquery
				return `_id =="${this.id}"`
			}
		},
		onLoad(event) {
			console.log(event.id);
			// event = {"id":"60783c5cb781700001375672","title":"阿里小程序IDE官方内嵌uni-app，为开发者提供多端开发服务","excerpt":"阿里小程序IDE官方内嵌uni-app，为开发者提供多端开发服务","avatar":"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-aliyun-gacrhzeynhss7c6d04/249516a0-3941-11eb-899d-733ae62bed2f.jpg"}
			//获取真实新闻id，通常 id 来自上一个页面
			if (event.id) {
				this.id = event.id
				this.goodWhere = "_id=='"+event.id+"'"
				console.log(this.goodWhere)
			}
			db.collection("t_shop_goods")
			  .where({
			    _id: event.id //传统MongoDB写法，不是jql写法。实际开发中推荐使用jql写法
			  }).get()
			  .then((res)=>{
				  let goods = res.result.data[0]
				  console.log(goods)
				  this.goods = goods
				  console.log(res.result.data[0].gallery)
				  const gallery = res.result.data[0].gallery.split(',')
				  for (var index in gallery) {
				  	this.thumb.push('https://zhy-demo.oss-cn-hangzhou.aliyuncs.com/upload/' + gallery[index])
				  	console.log(this.thumb)
				  }
			    // res 为数据库查询结果
			  }).catch((err)=>{
			    console.log(err.code); // 打印错误码
					console.log(err.message); // 打印错误内容
			  })
			  // 根据用户数据更新收藏状态
			favoriteDB.where(`"id_goods" == "${this.id}" && "id_user"==$env.uid`).get().then(res => {
				console.log("favorite")
				if (res.result.data.length == 0) {
					this.options[1].info = null
					this.optionsKey = !this.optionsKey
				} else {
					this.options[1].info = 1
					this.optionsKey = !this.optionsKey
				}
			})
		},
		onReady() {
			// 开始加载数据，修改 where 条件后才开始去加载 clinetDB 的数据 ，需要等组件渲染完毕后才开始执行 loadData，所以不能再 onLoad 中执行
			if (this.id) { // ID 不为空，则发起查询
				
			} else {
				uni.showToast({
					icon: 'none',
					title: this.$t('listDetail.newsErr')
				})
			}
		},
		onNavigationBarButtonTap(event) {
			if (event.type == 'share') {
				this.shareClick();
			}
		},
		methods: {
			onClick(e) {
				uni.showToast({
					title: `点击${e.content.text}`,
					icon: 'none'
				})
				if(e.content.text == "收藏") {
					this.setFavorite()
				}
			},
			buttonClick(e) {
				this.$refs.popup.open()
				// this.showSku = true;
				if(e.index == 0) {
					this.actionType = "cart";
				} else {
					this.actionType = "buy";
				}
			},
			formatPrice(price) {
				return '¥' + (price / 100).toFixed(2)
			},
			$log(...args){
				console.log('args',...args,this.id)
			},
			setReadNewsLog(){
				let item = {
					"article_id":this.id,
					"last_time":Date.now()
				},
				readNewsLog = uni.getStorageSync('readNewsLog')||[],
				index = -1;
				readNewsLog.forEach(({article_id},i)=>{
					if(article_id == item.article_id){
						index = i
					}
				})
				if(index === -1){
					readNewsLog.push(item)
				}else{
					readNewsLog.splice(index,1,item)
				}
				uni.setStorageSync('readNewsLog',readNewsLog)
				console.log(readNewsLog);
			},
			setFavorite() {
				if ( uniCloud.getCurrentUserInfo().tokenExpired < Date.now() ){
					return console.log('未登录用户');
				}
				favoriteDB.where(`"id_goods" == "${this.id}" && "id_user"==$env.uid`).get().then(res => {
					console.log(res.result.data.length)
					if (res.result.data.length == 0) {
						this.options[1].info = 1
						this.optionsKey = !this.optionsKey
						favoriteDB.add({
							id_goods: this.id,
							id_user: db.getCloudEnv('$cloudEnv_uid')	
						})
					} else {
						this.options[1].info = null
						this.optionsKey = !this.optionsKey
						favoriteDB.where(`"id_goods" == "${this.id}" && "id_user"==$env.uid`).remove()
					}
				})
				let last_time = Date.now();
				let article_id = this.id
				console.log({article_id,last_time});
				readNewsLog.where(`"article_id" == "${article_id}" && "user_id"==$env.uid`)
					.update({last_time})
					.then(({result:{updated}}) => {
						console.log('updated',updated);
						if (!updated) {
							readNewsLog.add({article_id}).then(e=>{
								console.log(e);
							}).catch(err => {
								console.log(err);
							})
						}
					}).catch(err => {
						console.log(err);
					})
			},
			loadData(data) {
			},
			/**
			 * followClick
			 * 点击关注
			 */
			followClick() {
				uni.showToast({
					title:this.$t('listDetail.follow'),
					icon: 'none'
				});
			},
			/**
			 * 分享该文章
			 */
			action() {
				console.log(this.actionType)
				if (this.actionType == "cart") {
					this.addToCart()
				} else if(this.actionType == "buy"){
					this.buy()
				}
			},
			addToCart() {
				dbCart.where({id_goods: dbCmd.eq(this.goods._id), id_user: dbCmd.eq(db.getCloudEnv('$cloudEnv_uid'))}).get().then(res => {
					if (res.result.data.length == 0) {
						dbCart.add({
							id_goods: this.goods._id,
							count: this.count,
							id_sku: "null",
							id_user: db.getCloudEnv('$cloudEnv_uid'),
							create_time: Date.now(),
							modify_time: Date.now()
						})
					} else {
						console.log(res.result.data)
						let cart = res.result.data[0]
						dbCart.where({_id: cart._id}).update({
							count: this.count + cart.count,
							modify_time: Date.now()
						})
					}
				}).then(res => {
					uni.showToast({
						title: "购物车添加成功",
						icon: 'none'
					})
					this.$refs.popup.close()
				})
			},
			buy() {
				// let idSku = '';
				// if (!this.sku.none_sku) {
				// 	idSku = this.sku.sel.id;
				// 	if(!idSku){
				// 		this.$u.toast('请选择商品规格')
				// 		return ;
				// 	}
				// }
				console.log("in")
				dbCart.where({id_goods: dbCmd.eq(this.goods._id), id_user: dbCmd.eq(db.getCloudEnv('$cloudEnv_uid'))}).get().then(res => {
					if (res.result.data.length == 0) {
						dbCart.add({
							id_goods: this.goods._id,
							count: this.count,
							id_sku: "null",
							id_user: db.getCloudEnv('$cloudEnv_uid'),
							create_time: Date.now(),
							modify_time: Date.now()
						})
					} else {
						console.log(res.result.data)
						let cart = res.result.data[0]
						dbCart.where({_id: cart._id}).update({
							count: this.count + cart.count,
							modify_time: Date.now()
						})
					}
				}).then(res => {
					console.log("success")
					uni.switchTab({
						url: '/pages/cart/cart'
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 30rpx;
	
		.title {
			font-size: 32rpx;
		}
	
		.desc {
			font-size: 12px;
			color: #999999;
			letter-spacing: 0;
			line-height: 18px;
			margin: 6px 0;
		}
	
		.price {
			color: #FA3534;
			font-size: 24rpx;
		}
	
		.express {
			color: #999;
			font-size: 24rpx;
			padding: 10rpx 0rpx;
		}
	}
	.goods-carts {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: column;
			position: fixed;
			left: 0;
			right: 0;
			/* #ifdef H5 */
			left: var(--window-left);
			right: var(--window-right);
			/* #endif */
			bottom: 0;
		}
	
	.header-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		font-size: 14px;
	}

	/* 标题 */
	.uni-title {
		display: flex;
		margin-bottom: 5px;
		font-size: 14px;
		font-weight: bold;
		color: #3b4144;
	}

	/* 描述 额外文本 */
	.uni-note {
		color: #999;
		font-size: 12px;

		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
	}

	.footer {
		display: flex;
		align-items: center;
	}

	.footer-button {
		display: flex;
		align-items: center;
		font-size: 12px;
		height: 30px;
		color: #fff;
		background-color: #ff5a5f;
	}

	.banner {
		position: relative;
		margin: 0 15px;
		height: 180px;
		overflow: hidden;
	}

	.banner-img {
		position: absolute;
		width: 100%;
	}

	.banner-title {
		display: flex;
		align-items: center;
		position: absolute;
		padding: 0 15px;
		width: 100%;
		bottom: 0;
		height: 30px;
		font-size: 14px;
		color: #fff;
		background: rgba(0, 0, 0, 0.4);
		overflow: hidden;
		box-sizing: border-box;
	}

	.uni-ellipsis {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.article-title {
		padding: 20px 15px;
		padding-bottom: 0;
	}

	.article-content {
		padding: 15px;
		font-size: 15px;
		overflow: hidden;
	}
	
	.sku {
		padding: 24rpx 32rpx;
	
		.goods {
			.right {
				padding-left: 20rpx;
	
				.price {
					color: #FA3534;
					font-size: 34rpx;
				}
	
				.stock {
					margin-top: 8px;
					color: #969799;
					font-size: 12px;
	
					.stock_num {
						margin-right: 16rpx;
						margin-left: 16rpx;
					}
				}
	
				.tips {
					margin-top: 8px;
					color: #969799;
					font-size: 12px;
					line-height: 16px;
				}
	
	
			}
		}
	
		.sku-list {
	
			.tree {
				margin-top: 30rpx;
	
				.title {
					padding-bottom: 12px;
				}
			}
	
			.node-list {
				.node {
					justify-content: center;
					min-width: 80rpx;
					margin: 0 24rpx 24rpx 0;
					line-height: 24rpx;
					vertical-align: middle;
				}
			}
		}
	
		.count {
			display: flex;
			justify-content: space-between;
			padding: 24rpx 0rpx;
			overflow: hidden;
			line-height: 60rpx;
			padding-bottom: 60rpx;
	
		}
	}
</style>
